package com.baseweb.webadmin.controller.admin;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.Constants;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.service.RoleRescService;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/resc")
public class RescController extends BaseController {
    private String prefix = "/resc";
    @Autowired
    private RoleRescService roleRescService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;


    /**
     * 展示资源
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewRescs", method = RequestMethod.GET)
    public String viewRescs(Model model) {
        List<Resc> rescList = roleRescService.selectRescs();
        model.addAttribute("rescList", rescList);
        return prefix + "/viewRescs";
    }

    /**
     * 跳转添加资源页面
     */
    @RequestMapping(value = "/rescManager", method = RequestMethod.GET)
    public String rescManager(Model model) {
   /*     List <Resc> rescsList = getRescListByRole();
        boolean flag = false;
        for (Resc resc:rescsList){
            if(("/resc:addResc").equals(resc.getResString())||("/resc:updateResc").equals(resc.getResString())||("/resc:deleteResc").equals(resc.getResString())){
               flag = true;
                break;
            }
        }*/
        //  model.addAttribute("flag",flag);
        return prefix + "/rescManager";
    }

    /**
     * 跳转添加资源页面
     */
    @RequestMapping(value = "/addRescView", method = RequestMethod.GET)
    public String addRescView() {
        return prefix + "/addRescView";
    }

    /**
     * 添加资源
     */
    @RequestMapping(value = "/addResc", method = RequestMethod.POST)
    public void addResc(@RequestParam("name") String name,
                        @RequestParam("resString") String resString,
                        @RequestParam("showUrl") String showUrl,
                        @RequestParam("priority") Integer priority,
                        @RequestParam("descn") String descn,
                        @RequestParam("showMenu") Integer showMenu,
                        @RequestParam("fatherId") Integer fatherId,
                        Model model, HttpServletRequest request) {
        boolean success = true;
        Resc resc = new Resc();
        resc.setName(name);
        resc.setResString(resString);
        resc.setShowUrl(showUrl);
        resc.setPriority(priority);
        resc.setDescn(descn);
        resc.setShowMenu(showMenu);
        resc.setFatherId(fatherId);
        Resc currentResc = null;
        try {
            roleRescService.insertResc(resc);
            currentResc = roleRescService.selectRescByNameAndResString(name, resString);

            //将新资源权限默认授予给超级管理
            RoleExample example = new RoleExample();
            RoleExample.Criteria criteria = example.createCriteria();
            criteria.andParentIdEqualTo(0);
            List<Role> roles = roleService.selectByExample(example);
            for (Role r : roles) {
                RescRoleKey rescRole = new RescRoleKey();
                rescRole.setRescId(currentResc.getId());
                rescRole.setRoleId(r.getId());
                roleRescService.insertRescRole(rescRole);
            }

            writeLog(request, Constants.ADD_RESOURCE, Constants.ADD_RESOURCE + "(资源名:" + name + ",资源ID:" + currentResc.getId() + ")", getUserName());     //记录历史

        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        }
        model.addAttribute("success", success);
        model.addAttribute("currentResc", currentResc);
        return;
    }

    /**
     * 跳转修改资源页面
     *
     * @param rescId
     * @param model
     * @return
     */
    @RequestMapping(value = "/updateRescView", method = RequestMethod.GET)
    public String updateRescView(@RequestParam("rescId") Integer rescId,
                                 Model model) {
        Resc resc = roleRescService.selectRescById(rescId);
        model.addAttribute("resc", resc);
        return prefix + "/updateRescView";
    }

    /**
     * 修改资源
     *
     * @param rescId
     * @param name
     * @param resString
     * @return
     */
    @RequestMapping(value = "/updateResc", method = RequestMethod.POST)
    public void updateResc(@RequestParam("rescId") Integer rescId,
                           @RequestParam("name") String name,
                           @RequestParam("resString") String resString,
                           @RequestParam("showUrl") String showUrl,
                           @RequestParam("priority") Integer priority,
                           @RequestParam("descn") String descn,
//                           @RequestParam("fatherId") Integer fatherId,
                           @RequestParam("showMenu") Integer showMenu,
                           Model model, HttpServletRequest request) {
        boolean success = true;

        Resc oldResc = roleRescService.selectRescById(rescId);

        Resc resc = new Resc();
        resc.setId(rescId);
        resc.setName(name);
        resc.setResString(resString);
        resc.setShowUrl(showUrl);
        resc.setPriority(priority);
        resc.setDescn(descn);
        resc.setShowMenu(showMenu);
//        resc.setFatherId(fatherId);

        //信息封装
        String oldInfo = "原始信息:资源名:" + oldResc.getName() + ",资源ShowUrl:" + oldResc.getShowUrl() + ",资源ResString:" + oldResc.getResString() + ",资源FatherId:" + oldResc.getFatherId();
        String newInfo = "修改信息:资源名:" + name + ",资源ShowUrl:" + showUrl + ",资源ResString:" + resString;

        try {
            roleRescService.updateResc(resc);
            writeLog(request, Constants.UPDATE_RESOURCE, Constants.UPDATE_RESOURCE + "(资源名:" + name + ",资源ID:" + rescId + ")" + "<br>" + "详细信息:<br>" + oldInfo + "<br>" + newInfo, getUserName());     //记录历史
        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        }
        model.addAttribute("success", success);
        model.addAttribute("currentResc", resc);
    }

    /**
     * 删除资源
     *
     * @param rescId
     * @param model
     * @return
     */
    @RequestMapping(value = "/deleteResc", method = RequestMethod.GET)
    public void deleteResc(@RequestParam("rescId") Integer rescId,
                           Model model, HttpServletRequest request) {

        boolean success = true;
        try {
            deleteRescRecursive(request, rescId);
        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        }
        model.addAttribute("success", success);
    }

    //递归地删除资源
    private void deleteRescRecursive(HttpServletRequest request, Integer rescId) {
        List<Resc> tempRescList = null;
        tempRescList = roleRescService.getRescByFatherId(rescId);
        for (Resc resc : tempRescList) {
            deleteRescRecursive(request, resc.getId());
        }
        roleRescService.deleteRescRoleByRescId(rescId);
        roleRescService.deleteRescById(rescId);
        writeLog(request, Constants.DELETE_RESOURCE, Constants.DELETE_RESOURCE + "资源ID:" + rescId + ")", getUserName());     //记录历史
    }


    /**
     * 判断资源是否存在
     *
     * @param name
     * @param model
     * @return
     */
    @RequestMapping(value = "/isResc", method = RequestMethod.GET)
    public String isResc(@RequestParam("name") String name,
                         Model model) {
        try {
            name = URLDecoder.decode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Boolean isResc = roleRescService.selectRescByName(name);
        model.addAttribute("isResc", isResc);
        return null;
    }

    /**
     * 根据当前用户初始化资源树
     *
     * @param model
     * @author:wxy
     * @time:2013-05-21
     */

    @RequestMapping(value = "/getResourceListByRole")
    public void getResourceListByRole(Model model) {
        List<Resc> rescsList = getRescListByRole();
        model.addAttribute("list", rescsList);

    }

    /**
     * 更加用户角色查找所有资源
     *
     * @return
     */
    private List<Resc> getRescListByRole() {
        User currentUser = userService.selectByName(getUserName());  //获得当前用户
        List<Role> currentRoles = roleService.selectRoleListByUser(currentUser.getId().toString());   //根据当前用户活动当前用户的所有角色

        List<Integer> resourceIdList = new ArrayList<Integer>();
        List<RescRoleKey> keys = new ArrayList<RescRoleKey>();
        //获取当前角色的资源 id
        for (Role role : currentRoles) {
            keys = roleRescService.selectRescRoleKeyByRoleId(role.getId());
            for (RescRoleKey key : keys) {
                if (!resourceIdList.contains(key)) {
                    resourceIdList.add(key.getRescId());
                }
            }
        }
        List<Resc> rescsList = roleRescService.getRescByIds(resourceIdList);
        return rescsList;
    }

}
